/**
 * @author dnguyen
 */
package climspace.client;


import java.io.File;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import climspace.ejb.Constants;
import climspace.ejb.UploadStationInterface;

public class CAPAPortalClient {

	private Context ctx;
	private UploadStationInterface svc;
	private String host = "localhost";

	public void setHost(String host) {
		this.host = host;
	}

	private Context getContext() throws Exception {
		if (ctx != null)
			return ctx;

		Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://" + host + ":1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		ctx = new InitialContext(props);

		return ctx;
	}

	private UploadStationInterface connectToService() throws Exception {
		if (svc != null)
			return svc;

		Context ctx = getContext();
		Object ref = ctx.lookup("UploadStationBean/remote");
		svc = (UploadStationInterface) PortableRemoteObject.narrow(ref, UploadStationInterface.class);

		return svc;
	}
	
	public void processFile(String weatherStationFileName, String weatherDataFileName) throws Exception {
		if (weatherStationFileName != null || !"".equals(weatherStationFileName)) {
			File file = new File(weatherStationFileName);
			if (file.exists()) {
				UploadStationInterface svr = connectToService();
				svr.processFile(weatherStationFileName,
						Constants.WEATHER_STATION_FILE);
			}
		}

		if (weatherDataFileName != null || !"".equals(weatherDataFileName)) {
			File file = new File(weatherDataFileName);
			if (file.exists()) {
				UploadStationInterface svr = connectToService();
				svr.processFile(weatherDataFileName,
						Constants.WEATHER_DATA_FILE);
			}
		}
	}

		
	public static void main(String[] args) {
		if (args.length != 2)
			throw new RuntimeException("Incorrent number of parameter");
		
		String weatherStationFileName = args[0];
		String weatherDataFileName = args[1];

		CAPAPortalClient capaPortalClient;
		
				capaPortalClient = new CAPAPortalClient();
				try {
					capaPortalClient.processFile(weatherStationFileName,
							weatherDataFileName);
					System.out.println("File has been uploaded!");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
}
